class VastApi
  class Attributes
    class Entry < Hash
      attr_reader :doc, :vast
      def initialize(vast,doc)
        @attributes = {}
        @doc = doc
        @vast = vast
        @doc.xpath("v:attribute/v:value").each do |value|
          self[value["id"]] = { :name => value.content, :count => value["count"] }
        end
      end

      def attribute(var_name)
        @attributes[var_name] ||=
          if %W{author updated}.index(var_name)
            self.send(var_name)
          elsif %W{ title id content }.index(var_name)
            get_var('xmlns:'+var_name)
          else
            get_var("v:#{var_name}")
          end
      end

      def author
        @attributes['author'] ||= get_children(@doc.at_xpath('xmlns:author'))
      end

      def updated
        @attributes["updated"] ||= DateTime.strptime(@doc.at_xpath('xmlns:updated').content)
      end

      private

      def get_var(var_name)
        if var = @doc.at_xpath(var_name)
          var.text
        else
          nil
        end
      end

      def get_children(var)
        hash = {}
        var.children.each do |item|
          hash[item.name] = item.content
        end
        hash
      end

    end
  end
end
